
import React, { Component } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Divider, Modal, Form, Input, Row, Col, Card, message, Switch, DatePicker, TimePicker} from 'antd';
import { connect } from 'dva';
import moment from 'moment';
// import styles from './style.less';

import PublicTableWrapper from '@/components/TableForm'

function beautySub(str, len) {
    const reg = /[\u4e00-\u9fa5]/g
    const slice = str.substring(0, len)
    // eslint-disable-next-line no-bitwise
    const chineseCharNum = (~~(slice.match(reg) && slice.match(reg).length))
    const realen = slice.length*2 - chineseCharNum
    return str.substr(0, realen) + (realen < str.length ? "..." : "")
}


const routes = [
    {
      path: '',
      breadcrumbName: 'Settings',
    },
    {
      path: '',
      breadcrumbName: 'ACK setup',
    }
]

@connect(({ setupandack }) => ({
    setupandack
}))


class SetAck extends Component {
    state = {
        visible: false,
        columns: [
            {
                title: 'ACK parameter',
                dataIndex: 'name',
                render: (_, record) => (
                    <span style={{color: '#000'}}>{`c01 : ${record.name.split(",")[0]}，c02 : ${record.name.split(",")[1]}，c03 : ${record.name.split(",")[2]}`}</span>
                )
            },
            {
                title: 'Actvt time',
                dataIndex: 'currentAckTime',
                render: (_, record) => (
                    <span>{moment.utc(Number(record.currentAckTime)).format("YYYY-MM-DD hh:mm:ss")}</span>
                )
            },
            {
                title: 'Application scope',
                dataIndex: 'range',
                render: (_, record) => (
                    <>
                        <a>{beautySub(record.range.join('、'), 9)}</a>
                    </>
                ),
            },
            // {
            //     title: '启/停用',
            //     dataIndex: 'status',
            //     align: 'center',
            //     render: (_, record) => (
            //         <>
            //             <Switch
            //                 checkedChildren="开"
            //                 unCheckedChildren="关"
            //                 defaultChecked
            //                 checked={!!record.status}
            //                 onChange={() => this.statusOnchange(record)}
            //             />
            //         </>
            //     ),
                
            // },
            {
                title: 'Operation',
                dataIndex: 'option',
                valueType: 'option',
                render: (_, record) => (
                    <>
                        <a
                            onClick={() => this.setHandleClick(_, record)}
                        >
                            
                            setup
                        </a>
                        <Divider type="vertical" />
                        <a 
                            style={{color: 'red'}}
                            onClick={() => this.showConfirm(record)}
                        >
                            delete
                        </a>
                    </>
                ),
            },
        ],

        // 表格
        loading: false,
        data: [],
        page: 1,
        pageSize: 10,
        search: "",
        totalCount: 1,

        // 修改的ack
        modifyAck: {}
    }

    componentDidMount () {
        this.initfetch()
    }

    initfetch = () => {
        const { dispatch } = this.props
        const { page, pageSize, search } = this.state
        this.setState({loading: true})
        dispatch({
            type: 'setupandack/fetch',
            payload: {
                limit: pageSize,
                offset: (page - 1) * pageSize,
                search,
              },
        }).then(res => {
            if (res && res.status === 200) {
                this.setState({
                    data: res.data,
                    loading: false,
                    totalCount: res.totalPageSize,
                })
            } else {
                this.setState({
                    data: [],
                    loading: false,
                    totalCount: 0,
                })
            }

        })
    }

    showConfirm = record => {
        const { dispatch } = this.props
        const isThis = this
        Modal.confirm({
            title: 'confirm deletion',
            content: (<div><span style={{color: 'red'}}>The deletion is irrevocable.</span><span style={{color: '#5E5E5E'}}>Do you want to continue?</span></div>),
            onOk() {
                dispatch({
                    type: 'setupandack/deleteAck',
                    payload: record
                }).then(res => {
                    if (res.status === 200) {
                        message.success('success')
                        isThis.initfetch()
                    }
        
                })
                
            },
            onCancel() {},
        })
    }

    statusOnchange = record => {
        // dispatch请求成功后
        const { data } = this.state
        // eslint-disable-next-line array-callback-return
        data.map(values => {
            if (values.key === record.key) {
                // eslint-disable-next-line no-param-reassign
                values.status = !values.status
            }
        })
        this.setState({
            data
        })
    }

    // 换页
    paginationChange = (page, pageSize) => {
        this.setState({
            page,
            pageSize,
        })
        
        const { dispatch } = this.props
        const { search } = this.state
        this.setState({loading: true})
        dispatch({
            type: 'setupandack/fetch',
            payload: {
                limit: pageSize,
                offset: (page - 1) * pageSize,
                search,
              },
        }).then(res => {
            if (res && res.status === 200) {
                this.setState({
                    data: res.data,
                    loading: false
                })
            } else {
                this.setState({
                    data: [],
                    loading: false,
                    totalCount: 0,
                })
            }

        })

    }
    

    onCancel = () => {
        this.setState({visible: false})
    }

    onCreate = () => {
        // this.setState({visible: false})
        const { form, dispatch } = this.props
        form.validateFields((err, values) => {
            if (err) { return}
            const ack = []
            ack.push(values.c01)
            ack.push(values.c02)
            ack.push(values.c03)
            const data = {
                ...values,
                Id: this.state.modifyAck.id,
                ack,
                day: moment(`${values.day.format('YYYY-MM-DD')} ${values.time.format('hh:mm:ss')}`).valueOf(),
                switch: (values.switch || values.switch === undefined) ? 1 : 0,
                Scope: this.state.modifyAck.range

            }

            dispatch({
                type: 'setupandack/modifyAck',
                payload: data
            }).then(res => {
                if (res.status === 200) {
                    this.setState({visible: false})
                    this.initfetch()
                }

            })
            // console.log(values.day.format('YYYY-MM-DD'))
            // console.log(values.time.format('hh:mm:ss'))
            // console.log(moment(`${values.day.format('YYYY-MM-DD')} ${values.time.format('hh:mm:ss')}`).valueOf())

        })
    }

    setHandleClick = (_, record) => {
        const { form } = this.props
        this.setState({visible: true, modifyAck: {...record}})
        const data = {
            c01: record.name.split(",")[0],
            c02: record.name.split(",")[1],
            c03: record.name.split(",")[2],
        }
        form.setFieldsValue({
            ...data,
            // day: moment(moment(Number(record.currentAckTime)).format("YYYY-MM-DD")),
            day: moment.utc(Number(record.currentAckTime)),
            time: moment.utc(Number(record.currentAckTime)),
            switch: record.status
        })
    }

    render () {
        const { form } = this.props
        const { getFieldDecorator } = form
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 14 },
        }

        return (
            <PageHeaderWrapper title="ACK setup" breadcrumb={{ routes }}>
                <Card>

                    {/* <Button icon="plus" type="primary" style={{margin: '10px 0'}} onClick={this.showModal}>新增网关</Button> */}

                    {/* <TableComponents
                        loading={this.state.loading}
                        columns={this.state.columns}
                        data={this.state.data}
                        currentpageSize={this.state.pageSize}
                        currentPage={this.state.currentPage}
                        total={this.state.total}
                        paginationChange= {(page, pageSize) => this.paginationChange(page, pageSize)}
                    /> */}
                    <PublicTableWrapper
                        loading={this.state.loading}
                        columns={this.state.columns}
                        data={this.state.data}
                        currentpageSize={this.state.pageSize}
                        total={this.state.totalCount}
                        paginationChange={(page, pageSize) => this.paginationChange(page, pageSize)}
                    />
                </Card>


                <Modal
                    visible={this.state.visible}
                    title="ACK setup"
                    onCancel={this.onCancel}
                    onOk={this.onCreate}
                    forceRender
                >
                    <Form style={{ margin: '0 auto' }}>
                        <Row gutter={24}>
                            <Col span={24}>
                                <Form.Item label="c02 RptIntvl" {...formItemLayout} >
                                    {getFieldDecorator('c01', {
                                    rules: [{ required: true, message: 'Input C01 parameter!' }],
                                    })(<Input placeholder="Input C01 parameter" />)}
                                </Form.Item>
                            </Col>
                            <Col span={24}>
                                <Form.Item label="c48 ScanIntvl" {...formItemLayout} >
                                    {getFieldDecorator('c02', {
                                    rules: [{ required: true, message: 'Input C02 parameter!' }],
                                    })(<Input placeholder="Input C02 parameter" />)}
                                </Form.Item>
                            </Col>
                            <Col span={24}>
                                <Form.Item label="c58 ScanWindw" {...formItemLayout} >
                                    {getFieldDecorator('c03', {
                                    rules: [{ required: true, message: 'Input C03 parameter!' }],
                                    })(<Input placeholder="Input C03 parameter" />)}
                                </Form.Item>
                            </Col>

                            <Col span={24}>
                                <Form.Item label="Actvt date" {...formItemLayout} >
                                    {getFieldDecorator('day', {
                                    rules: [{ required: true, message: 'Actvt date!' }],
                                    })(
                                        <DatePicker style={{ width: '99%' }} placeholder="Actvt date" />
                                    )}
                                </Form.Item>
                            </Col>

                            <Col span={24}>
                                <Form.Item label="Actvt time" {...formItemLayout} >
                                    {getFieldDecorator('time', {
                                    rules: [{ required: true, message: 'Actvt time!' }],
                                    })(
                                        <TimePicker style={{ width: '99%' }} placeholder="Actvt time" />
                                    )}
                                </Form.Item>
                            </Col>

                            <Col span={24}>
                                <Form.Item label="On/Off" {...formItemLayout} >
                                    {getFieldDecorator('switch', {
                                    })(
                                        <Switch
                                            checkedChildren="On"
                                            unCheckedChildren="Off"
                                            defaultChecked
                                            // checked
                                        />
                                        
                                    )}
                                </Form.Item>
                            </Col>
                                

                            
                            
                        </Row>
                    </Form>
                </Modal>
            </PageHeaderWrapper>
        )

    }

}



export default Form.create()(SetAck)